<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { updateProcureApi, updateStockApi, checkStockApi } from '@/apis/order'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

interface Props {
  visible: boolean,
  info: any
}

const props = defineProps<Props>()
const emit = defineEmits(['confirm', 'update:visible'])

const formData = ref({
  status: 4,
  ch_order_repair: ''
})

/** 关闭弹窗 */
const handleClose = () => {
  formData.value = {
    status: 4,
    ch_order_repair: ''
  }
  emit('update:visible', false)
  console.log('关闭')
}

const handleConfirm = async () => {
   // 修改库存
   if(formData.value.status === 4 && props.info.open_inventory === 1) {
    const stockRes = await checkStockApi({
      shop_sku: props.info.shop_sku
    })

    // 判断库存
    if (stockRes.shop_inventory <= 0) return ElMessage.error('库存不足')

    // 修改库存
    await updateStockApi({
      shop_sku: props.info.shop_sku,
      shop_inventory: stockRes.shop_inventory - props.info.order_quantity
    })
  }

  let ch_order_repair = formData.value.ch_order_repair
  if (ch_order_repair) {
    const oldRepairList = JSON.parse(props.info.ch_order_repair || '[]')
    ch_order_repair = JSON.stringify([...oldRepairList, {time: new Date().toLocaleString(), content: ch_order_repair, userName: userStore.getUserInfo.nickname }])
  }

  const res = await updateProcureApi({...props.info, ...formData.value, ch_order_repair})

 
  ElMessage.success(res.msg)
  emit('confirm')
  handleClose()
}
</script>

<template>
  <el-dialog :model-value="visible" title="编辑收货信息" width="500" @close="handleClose">
    <!-- 对话框内容插槽 -->
    <el-form label-width="100" label-position="left">
      <el-form-item label="订单是否异常">
        <el-radio-group v-model="formData.status">
          <el-radio :label="4">正常</el-radio>
          <el-radio :label="3">异常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="异常说明" v-if="formData.status === 3">
        <el-input type="textarea" v-model="formData.ch_order_repair" placeholder="请输入异常说明" />
      </el-form-item>
    </el-form>

    <!-- 自定义底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
